﻿#include "rider-orderPage.h"

OrderPage::OrderPage(database &db, QWidget *parent)
    : QWidget(parent), db(db), userPhoneId(-1), userIdentity(-1)
{
    setupUI();
    setUserInfo(userPhoneId,userIdentity);
}

OrderPage::~OrderPage()
{
}

void OrderPage::setupUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 创建标题
    titleLabel = new QLabel("骑手后台 - 可接订单列表");
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 18pt; font-weight: bold; color: #333;");

    // 创建刷新按钮
    refreshButton = new QPushButton("刷新订单");
    refreshButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "   border-radius: 5px;"
        "   padding: 8px 15px;"
        "   font-size: 12pt;"
        "}"
        "QPushButton:hover {"
        "   background-color: #45a049;"
        "}"
    );

    // 连接刷新按钮信号
    connect(refreshButton, &QPushButton::clicked, this, &OrderPage::loadAvailableOrders);

    // 创建订单表格
    ordersTable = new QTableWidget(this);
    ordersTable->setColumnCount(8); // 商品名, 用户名, 地址, 商家名, 商家地址, 数量, 下单时间, 操作

    // 设置表头
    QStringList headers;
    headers << "商品名称" << "用户名" << "配送地址" << "商家名称" << "商家地址" << "数量" << "下单时间" << "操作";
    ordersTable->setHorizontalHeaderLabels(headers);

    // 调整表格样式
    ordersTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ordersTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ordersTable->setAlternatingRowColors(true);
    ordersTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ordersTable->verticalHeader()->setVisible(false);
    ordersTable->setStyleSheet(
        "QTableWidget {"
        "   border: 1px solid #ddd;"
        "   border-radius: 5px;"
        "   background-color: #fff;"
        "}"
        "QTableWidget::item {"
        "   padding: 5px;"
        "}"
        "QTableWidget::item:selected {"
        "   background-color: #e6f7ff;"
        "   color: #000;"
        "}"
        "QHeaderView::section {"
        "   background-color: #f2f2f2;"
        "   padding: 5px;"
        "   border: 1px solid #ddd;"
        "   font-weight: bold;"
        "}"
    );

    // 布局控件
    QHBoxLayout *headerLayout = new QHBoxLayout();
    headerLayout->addWidget(titleLabel, 1);
    headerLayout->addWidget(refreshButton, 0);

    mainLayout->addLayout(headerLayout);
    mainLayout->addWidget(ordersTable);
    
    // 添加已接订单标签
    QLabel *acceptedOrdersLabel = new QLabel("我已接的订单");
    acceptedOrdersLabel->setAlignment(Qt::AlignCenter);
    acceptedOrdersLabel->setStyleSheet("font-size: 16pt; font-weight: bold; color: #333; margin-top: 20px;");
    mainLayout->addWidget(acceptedOrdersLabel);
    
    // 创建已接订单表格
    acceptedOrdersTable = new QTableWidget(this);
    acceptedOrdersTable->setColumnCount(8); // 商品名, 用户名, 地址, 商家名, 商家地址, 数量, 下单时间, 操作
    
    // 设置表头
    QStringList acceptedHeaders;
    acceptedHeaders << "商品名称" << "用户名" << "配送地址" << "商家名称" << "商家地址" << "数量" << "下单时间" << "操作";
    acceptedOrdersTable->setHorizontalHeaderLabels(acceptedHeaders);
    
    // 调整表格样式
    acceptedOrdersTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    acceptedOrdersTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    acceptedOrdersTable->setAlternatingRowColors(true);
    acceptedOrdersTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    acceptedOrdersTable->verticalHeader()->setVisible(false);
    acceptedOrdersTable->setStyleSheet(
        "QTableWidget {"
        "   border: 1px solid #ddd;"
        "   border-radius: 5px;"
        "   background-color: #fff;"
        "}"
        "QTableWidget::item {"
        "   padding: 5px;"
        "}"
        "QTableWidget::item:selected {"
        "   background-color: #e6f7ff;"
        "   color: #000;"
        "}"
        "QHeaderView::section {"
        "   background-color: #f2f2f2;"
        "   padding: 5px;"
        "   border: 1px solid #ddd;"
        "   font-weight: bold;"
        "}"
    );
    
    mainLayout->addWidget(acceptedOrdersTable);
}

void OrderPage::setUserInfo(int phoneId, int userIdentity)
{
    this->userPhoneId = phoneId;
    this->userIdentity = userIdentity;

    // 只有骑手(userIdentity=3)才能查看并操作此页面
    if (userIdentity == 3) {
        loadAvailableOrders();
        loadAcceptedOrders();
    } else {
        // 如果不是骑手，隐藏所有控件
        this->hide();
    }
}

void OrderPage::loadAvailableOrders()
{
    // 清空表格内容
    ordersTable->setRowCount(0);

    // 查询待接单的订单
    QString sql = "SELECT o.order_id, c.com_name, u.user_name, o.address, b.business_name, "
                  "a.address, o.quantity, o.time_start FROM order_c o "
                  "JOIN commodity c ON o.com_id = c.com_id "
                  "JOIN user u ON o.user_id = u.user_id "
                  "JOIN business b ON o.business_id = b.business_id "
                  "JOIN address a ON b.address_id = a.address_id "
                  "WHERE o.cs_id = 5";
    qDebug()<<"orderPage-110:"<<sql;
    QSqlQuery query = db.exec(sql);

    int row = 0;
    while (query.next()) {
        // 获取订单信息
        int orderId = query.value(0).toInt();
        QString comName = query.value(1).toString();
        QString userName = query.value(2).toString();
        QString address = query.value(3).toString();
        QString businessName = query.value(4).toString();
        QString businessAddress = query.value(5).toString();
        int quantity = query.value(6).toInt();
        QString orderTime = query.value(7).toString();

        // 添加新行
        ordersTable->insertRow(row);

        // 添加数据到表格
        ordersTable->setItem(row, 0, new QTableWidgetItem(comName));
        ordersTable->setItem(row, 1, new QTableWidgetItem(userName));
        ordersTable->setItem(row, 2, new QTableWidgetItem(address));
        ordersTable->setItem(row, 3, new QTableWidgetItem(businessName));
        ordersTable->setItem(row, 4, new QTableWidgetItem(businessAddress));
        ordersTable->setItem(row, 5, new QTableWidgetItem(QString::number(quantity)));
        ordersTable->setItem(row, 6, new QTableWidgetItem(orderTime));

        // 添加接单按钮
        QPushButton *acceptButton = createAcceptButton(row);
        acceptButton->setProperty("order_id", orderId);

        QWidget *buttonWidget = new QWidget();
        QHBoxLayout *buttonLayout = new QHBoxLayout(buttonWidget);
        buttonLayout->addWidget(acceptButton);
        buttonLayout->setAlignment(Qt::AlignCenter);
        buttonLayout->setContentsMargins(0, 0, 0, 0);

        ordersTable->setCellWidget(row, 7, buttonWidget);

        row++;
    }

    // 如果没有可接订单，显示提示
    if (row == 0) {
        QMessageBox::information(this, "提示", "当前没有可接的订单");
    }
}

void OrderPage::loadAcceptedOrders()
{
    // 清空表格内容
    acceptedOrdersTable->setRowCount(0);
    
    // 获取骑手ID
    QString riderIdSql = QString("SELECT rider_id FROM rider WHERE phone_id = %1").arg(userPhoneId);
    QSqlQuery riderQuery = db.exec(riderIdSql);
    
    if (!riderQuery.next()) {
        return;
    }
    
    int riderId = riderQuery.value(0).toInt();
    
    // 查询已接单的订单
    QString sql = QString("SELECT o.order_id, c.com_name, u.user_name, o.address, b.business_name, "
                  "a.address, o.quantity, o.time_start, o.cs_id FROM order_c o "
                  "JOIN commodity c ON o.com_id = c.com_id "
                  "JOIN user u ON o.user_id = u.user_id "
                  "JOIN business b ON o.business_id = b.business_id "
                  "JOIN address a ON b.address_id = a.address_id "
                  "WHERE o.rider_id = %1 AND o.cs_id IN (6, 7)").arg(riderId);
    
    qDebug() << "orderPage-已接订单查询:" << sql;
    QSqlQuery query = db.exec(sql);
    
    int row = 0;
    while (query.next()) {
        // 获取订单信息
        int orderId = query.value(0).toInt();
        QString comName = query.value(1).toString();
        QString userName = query.value(2).toString();
        QString address = query.value(3).toString();
        QString businessName = query.value(4).toString();
        QString businessAddress = query.value(5).toString();
        int quantity = query.value(6).toInt();
        QString orderTime = query.value(7).toString();
        int statusId = query.value(8).toInt();
        
        // 添加新行
        acceptedOrdersTable->insertRow(row);
        
        // 添加数据到表格
        acceptedOrdersTable->setItem(row, 0, new QTableWidgetItem(comName));
        acceptedOrdersTable->setItem(row, 1, new QTableWidgetItem(userName));
        acceptedOrdersTable->setItem(row, 2, new QTableWidgetItem(address));
        acceptedOrdersTable->setItem(row, 3, new QTableWidgetItem(businessName));
        acceptedOrdersTable->setItem(row, 4, new QTableWidgetItem(businessAddress));
        acceptedOrdersTable->setItem(row, 5, new QTableWidgetItem(QString::number(quantity)));
        acceptedOrdersTable->setItem(row, 6, new QTableWidgetItem(orderTime));
        
        // 添加操作按钮
        QPushButton *actionButton;
        if (statusId == 6) { // 配送中
            actionButton = new QPushButton("标记为已送达");
            actionButton->setStyleSheet(
                "QPushButton {"
                "   background-color: #1890ff;"
                "   color: white;"
                "   border-radius: 3px;"
                "   padding: 5px 10px;"
                "}"
                "QPushButton:hover {"
                "   background-color: #40a9ff;"
                "}"
            );
            connect(actionButton, &QPushButton::clicked, this, &OrderPage::onDeliveredClicked);
        } else { // 已送达
            actionButton = new QPushButton("已完成");
            actionButton->setEnabled(false);
            actionButton->setStyleSheet(
                "QPushButton {"
                "   background-color: #52c41a;"
                "   color: white;"
                "   border-radius: 3px;"
                "   padding: 5px 10px;"
                "   opacity: 0.7;"
                "}"
            );
        }
        
        actionButton->setProperty("order_id", orderId);
        
        QWidget *buttonWidget = new QWidget();
        QHBoxLayout *buttonLayout = new QHBoxLayout(buttonWidget);
        buttonLayout->addWidget(actionButton);
        buttonLayout->setAlignment(Qt::AlignCenter);
        buttonLayout->setContentsMargins(0, 0, 0, 0);
        
        acceptedOrdersTable->setCellWidget(row, 7, buttonWidget);
        
        row++;
    }
}

QPushButton* OrderPage::createAcceptButton(int row)
{
    QPushButton *button = new QPushButton("接单");
    button->setStyleSheet(
        "QPushButton {"
        "   background-color: #1890ff;"
        "   color: white;"
        "   border-radius: 3px;"
        "   padding: 5px 10px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #40a9ff;"
        "}"
    );

    // 连接按钮点击信号
    connect(button, &QPushButton::clicked, this, &OrderPage::onAcceptOrderClicked);

    return button;
}

void OrderPage::onAcceptOrderClicked()
{
    // 获取发送信号的按钮
    QPushButton *button = qobject_cast<QPushButton *>(sender());
    if (!button) return;

    // 获取订单ID
    int orderId = button->property("order_id").toInt();

    // 获取骑手信息
    QString riderIdSql = QString("SELECT rider_id FROM rider WHERE phone_id = %1").arg(userPhoneId);
    qDebug()<<"orderPage-189-查询骑手id:"<<riderIdSql;
    QSqlQuery riderQuery = db.exec(riderIdSql);

    if (!riderQuery.next()) {
        QMessageBox::warning(this, "错误", "无法获取骑手信息，请确认您已注册为骑手");
        return;
    }

    int riderId = riderQuery.value(0).toInt();

    // 获取手机号
    QString phoneSql = QString("SELECT phone FROM phone WHERE phone_id = %1").arg(userPhoneId);
    qDebug()<<"orderPage-201-查询手机号:"<<phoneSql;
    QSqlQuery phoneQuery = db.exec(phoneSql);

    if (!phoneQuery.next()) {
        QMessageBox::warning(this, "错误", "无法获取联系电话");
        return;
    }

    QString phone = phoneQuery.value(0).toString();

    // 确认是否接单
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认接单",
                                 "确定要接此订单吗？接单后需要尽快配送。",
                                 QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        // 更新订单状态
        QString updateSql = QString("UPDATE order_c SET rider_id = %1, phone = '%2', cs_id = 6 "
                                   "WHERE order_id = %3")
                                   .arg(riderId)
                                   .arg(phone)
                                   .arg(orderId);
        qDebug()<<"orderPage-224-修改订单:"<<updateSql;
        QSqlQuery updateQuery = db.exec(updateSql);

        if (updateQuery.isActive()) {
            QMessageBox::information(this, "接单成功", "您已成功接单，请尽快配送");
            // 刷新订单列表
            loadAvailableOrders();
            loadAcceptedOrders();
        } else {
            QMessageBox::warning(this, "接单失败", "接单操作失败，请稍后重试");
        }
    }
}

void OrderPage::onDeliveredClicked()
{
    // 获取发送信号的按钮
    QPushButton *button = qobject_cast<QPushButton *>(sender());
    if (!button) return;
    
    // 获取订单ID
    int orderId = button->property("order_id").toInt();
    
    // 确认是否送达
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认送达",
                                 "确认订单已送达？",
                                 QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        // 更新订单状态为已送达
        QString updateSql = QString("UPDATE order_c SET cs_id = 7 WHERE order_id = %1").arg(orderId);
        qDebug() << "orderPage-标记送达:" << updateSql;
        QSqlQuery updateQuery = db.exec(updateSql);
        
        if (updateQuery.isActive()) {
            QMessageBox::information(this, "操作成功", "订单已标记为送达");
            // 刷新已接订单列表
            loadAcceptedOrders();
        } else {
            QMessageBox::warning(this, "操作失败", "标记送达失败，请稍后重试");
        }
    }
}
